#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "GenericClient.h"

#define N_ROUTINE 7
#define STR_LEN 5
#define BUF_SIZE 200
#define HEADER_SIZE 4

size_t CalcFromHeader(void* _header)
{
    return *((int*)_header);
}

int main()
{
    int                 i                   ;
    char                recvBuf[BUF_SIZE]   ;
    char                sendBuf[BUF_SIZE]   ;
    char                word[BUF_SIZE]      ;
    size_t              size                ;
    GenClient*          client = GenClientNew("127.0.0.1", 7, GC_TCP);

    if(!client)
    {
        perror("error on client new");
        return -1;
    }

    for(i = 0; i < N_ROUTINE; ++i)
    {
        puts("Enter message");
        scanf("%s", word);

        *(int*)sendBuf = strlen(word);
        strcpy(sendBuf + sizeof(int) , word);
        if(GenClientWrite(client, sendBuf, HEADER_SIZE + strlen(word)))
        {
            fprintf(stderr, "error occured on write\n");
            return -1;
        }


        if(GenClientRead(client, recvBuf ,HEADER_SIZE))
        {
            fprintf(stderr, "error occured on read\n");
            return -1;
        }
        size = CalcFromHeader(recvBuf);
        if(GenClientRead(client, recvBuf + HEADER_SIZE, size))
        {
            fprintf(stderr, "error occured on read\n");
            return -1;
        }
        *(recvBuf + HEADER_SIZE + size) = '\0';
        printf("%s\n", recvBuf + HEADER_SIZE);

    }


    return 0;
}
